import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:zhihuishop/pages/home/component/home_ad.dart';
import 'package:zhihuishop/pages/home/component/home_rich_text.dart';
import 'package:zhihuishop/pages/home/component/home_search_bar.dart';
import 'package:zhihuishop/pages/home/component/home_shop_list.dart';

import '../../utils/Http.dart';
import 'component/home_banner.dart';
import 'component/home_nav.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  Map resData = {};

  @override
  void initState() {
    super.initState();
    getHomeListData();
  }

  /// 获取首页整体列表数据
  void getHomeListData() async {
    var res = await Http.getInstance().get('?s=/api/page/detail');
    debugPrint(res.toString());
    setState(() {
      resData = res['data']['pageData'];
      debugPrint(resData['items'].toString());
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(
          '智慧商城',
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.red,
        centerTitle: true,
      ),
      body: EasyRefresh(
        child: ListView.builder(
          itemBuilder: (context, index) {
            if (index == 0) {
              return HomeSearchBar();
            } else if (resData['items'][index]['type'] == 'banner') {
              return HomeBanner(bannerList: resData['items'][index]['data']);
            } else if (resData['items'][index]['type'] == 'navBar') {
              return HomeNav(navList: resData['items'][index]['data']);
            } else if (resData['items'][index]['type'] == 'image') {
              return HomeAd(adList: resData['items'][index]['data']);
            } else if (resData['items'][index]['type'] == 'richText') {
              return HomeRichText();
            } else if (resData['items'][index]['type'] == 'goods') {
              return HomeShopList(goodsList: resData['items'][index]['data']);
            } else {
              return Container();
            }
          },
          shrinkWrap: true,
          // physics: const NeverScrollableScrollPhysics(),
          itemCount: resData['items']?.length ?? 0,
        ),
        header: const ClassicHeader(),
        footer: const ClassicFooter(),
        onRefresh: () async {
          await Future.delayed(const Duration(seconds: 2));
          getHomeListData();
        },
        onLoad: () async {
          await Future.delayed(const Duration(seconds: 2));
          getHomeListData();
        },
      ),
    );
  }
}
